# -*- coding:utf-8 -*-
import ctypes
import threading
import MySQLdb
import os
import socket
import json
import httplib
import urllib2
import urllib
import uuid
import zipfile
import base64
import sys
import hashlib
import datetime
import time
import subprocess
import xml.dom.minidom
import shutil
from os.path import join, getsize

def commom_log(filename, content , write_type='wb'):
    try:
        f = open(filename , write_type)
        f.write(content);
        f.close()
    except:
        print('happen an exception when write file')
        return ""

def get_version(random_filename):
    try:
        zf = zipfile.ZipFile(random_filename, "a")
        zf.getinfo("iTunesMetadata.plist")
        data = zf.read("iTunesMetadata.plist")
        if data :
            index   = data.rfind('bundleShortVersionString')
            if index != -1:
                index_right = data.find('</string>', index)
                version = data[index: index_right]
                version = version.replace("bundleShortVersionString</key>" , '').replace("<string>", "").strip()
            else:
                version = ''
            index   = data.rfind('bundleVersion')
            if index != -1:
                index_right = data.find('</string>', index)
                bundleVersion = data[index: index_right]
                bundleVersion = bundleVersion.replace("bundleVersion</key>" , '').replace("<string>", "").strip()
            else:
                bundleVersion = ''

            index   = data.rfind('itemId')
            if index != -1:
                index_right = data.find('</integer>', index)
                itunesid = data[index: index_right]
                itunesid = itunesid.replace("itemId</key>" , '').replace("<integer>", "").strip()
            else:
                itunesid = ''
            
            return  version,bundleVersion,itunesid
        else:
            return '','',''
    except:
        return '','',''


src_path = "/data/disk1/ipas_c/"
dst_path = "/data/app/jailbreak/"

while True:

    datetime_now = datetime.datetime.now()
    datetime_now = datetime_now.strftime("%Y-%m-%d")

    listfile=os.listdir(src_path)
    if len(listfile) > 0:
        for line in listfile:
            if line.rfind('.ipa') != -1:
                print unicode( src_path+line , "GBK" ) + "======\n"
                return_value    = get_version(unicode( src_path+line , "GBK" ))
                version_j       = return_value[0]
                bundleVersion_j = return_value[1]
                itunesid        = return_value[2]
                if itunesid != '':

                    # copy 一份文件到 ipas_bak 目录
                    m = hashlib.md5(str(itunesid)) 
                    m.digest()
                    md5_str = m.hexdigest()
                    str1 = md5_str[0: 2]
                    str2 = md5_str[2: 4]
                    
                    print dst_path + "/" + str(str1) + "/" + str(str2) + "/" + (str(itunesid))+".ipa"

                    shutil.move(src_path+line , dst_path + "/" + str(str1) + "/" + str(str2) + "/" + (str(itunesid))+".ipa")

                    commom_log('move_success.log' , str(itunesid) + "---" + dst_path + "/" + str(str1) + "/" + str(str2) + "/" + (str(itunesid))+".ipa" +  "\n" , 'a')
                else:
                    # 读取文件失败
                    print "not itunesid"
                    commom_log('read_ipas_error_'+datetime_now+'.log' , str(itunesid) + "---" + src_path + line +  "\n" , 'a')
        else:
            print "wait 10 min ..."
            time.sleep(10)